package com.ruoyi.system.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dyun.tool.mybatis.domain.PageDomain;
import com.ruoyi.common.annotation.SysLog;
import com.ruoyi.common.enums.BaseStatusEnum;
import com.ruoyi.common.enums.BusinessTypeEnum;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.project.system.entity.SysDictData;
import com.ruoyi.project.system.entity.SysDictType;
import com.ruoyi.project.system.service.ISysDictDataService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import lombok.AllArgsConstructor;
import net.dreamlu.mica.core.result.R;
import net.dreamlu.mica.core.utils.$;
import net.dreamlu.mica.core.validation.CreateGroup;
import net.dreamlu.mica.core.validation.UpdateGroup;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 字典编码 控制层
 *
 * @author dy
 */
@RestController
@RequestMapping("/system/dict/data")
@AllArgsConstructor
public class SysDictDataController extends BaseController {

    private final ISysDictTypeService sysDictTypeService;

    private final ISysDictDataService sysDictDataService;

    /**
     * 分页
     */
    @PreAuthorize("@ss.hasPermi('system:dict:list')")
    @GetMapping("/list")
    public R<IPage<SysDictData>> list(SysDictData sysDictData, PageDomain pageDomain) {
        IPage<SysDictData> pages = sysDictDataService.page(startPage(pageDomain), buildQueryWrapper(sysDictData));
        return success(pages);
    }

    /**
     * 字典
     */
    @GetMapping("/type")
    public R type(SysDictData sysDictData) {
        // 只查询未停用的
        SysDictType checkSysDictType = sysDictTypeService.getOne(new LambdaQueryWrapper<SysDictType>().eq(SysDictType::getDictType, sysDictData.getDictType()));
        if (checkSysDictType != null && BaseStatusEnum.DB_STATUS_DISABLE.getStatus().equals(checkSysDictType.getStatus())) {
            return success();
        }
        // 查询未停用的
        sysDictData.setStatus(BaseStatusEnum.DB_STATUS_NORMAL.getStatus());
        List<SysDictData> list = sysDictDataService.list(buildQueryWrapper(sysDictData));
        return success(list);
    }

    /**
     * 详情
     */
    @PreAuthorize("@ss.hasPermi('system:dict:query')")
    @GetMapping("/detail")
    public R<SysDictData> detail(Long id) {
        return success(sysDictDataService.getById(id));
    }

    /**
     * 新增
     */
    @SysLog(title = "字典数据", businessType = BusinessTypeEnum.INSERT)
    @PreAuthorize("@ss.hasPermi('system:dict:add')")
    @PostMapping("/add")
    public R add(@Validated(value = {CreateGroup.class}) @RequestBody SysDictData sysDictData) {
        return status(sysDictDataService.saveIgnore(sysDictData));
    }

    /**
     * 修改
     */
    @SysLog(title = "字典数据", businessType = BusinessTypeEnum.UPDATE)
    @PreAuthorize("@ss.hasPermi('system:dict:edit')")
    @PutMapping("/update")
    public R update(@Validated(value = {UpdateGroup.class}) @RequestBody SysDictData sysDictData) {
        return status(sysDictDataService.updateById(sysDictData));
    }

    /**
     * 删除
     */
    @SysLog(title = "字典数据", businessType = BusinessTypeEnum.DELETE)
    @PreAuthorize("@ss.hasPermi('system:dict:remove')")
    @DeleteMapping("/delete/{ids}")
    public R delete(@PathVariable Long[] ids) {
        List<SysDictData> sysDictDatas = new ArrayList<>();
        List<Long> idList = new ArrayList<>(Arrays.asList(ids));
        idList.forEach(v -> {
            SysDictData sysDictData = new SysDictData();
            sysDictData.setId(v);
            sysDictDatas.add(sysDictData);
        });
        boolean result = sysDictDataService.updateBatchById(sysDictDatas) && sysDictDataService.removeByIds(idList);
        return status(result);
    }

    private Wrapper<SysDictData> buildQueryWrapper(SysDictData sysDictData) {
        return new LambdaQueryWrapper<SysDictData>()
                .eq($.isNotBlank(sysDictData.getDictType()), SysDictData::getDictType, sysDictData.getDictType())
                .like($.isNotBlank(sysDictData.getDictLabel()), SysDictData::getDictLabel, sysDictData.getDictLabel())
                .eq($.isNotNull(sysDictData.getStatus()), SysDictData::getStatus, sysDictData.getStatus())
                .orderByAsc(SysDictData::getSeq);
    }
}
